<?php

declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\ProductCurrencyLink;
use app\admin\model\WholesalOrderItem as WholesalOrderItemModel;
use think\facade\Db;
use app\admin\model\Product as ProductModel;
use app\admin\model\ProductCurrencyLink as CurrencyLinkModel;
use app\admin\model\Warehouse as ModelWarehouse;

class WholesalAssets extends BaseService
{
    /**
     * 注册服务
     *
     * @return mixed
     */
    public function register()
    {
        //
    }

    /**
     * 执行服务
     *
     * @return mixed
     */
    public function boot()
    {
        //
    }

    /**
     * 资产列表
     * @param $param
     * @param $page
     * @param $limit
     * @return array
     * @throws \app\api\exception\ParameterException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 2024-12-24 14 08 42
     * author: jiang
     */
    public function index($param, $page, $limit)
    {
        $arrData = ['code' => 0, 'message' => 'success'];

        $where = [
            ['p.is_del', '=', 0],
            ['p.status', '=', 1],
            ['w.status', '=', 100],
            ['w.review_node', '=', 0],
            ['i.is_del', '=', 0],
            ['w.order_category', '=', 'wholesal']
        ];
        $where[] = ['i.quantity', '>', 0];
        if ($param['currency']) {
            $oCurrencyLinkModel = CurrencyLinkModel::where('currencyid', $param['currency'])->column('productid');
            $where[] = ['p.id', 'in', $oCurrencyLinkModel];
        }

        if ($param['product_name']) {
            $where[] = ['p.cname', 'like', '%' . $param['product_name'] . '%'];
        }

        if ($param['code']) {
            $where[] = ['p.code', 'like', '%' . $param['code'] . '%'];
        }
        if ($param['brand']) {
            $where[] = ['p.brand', '=', $param['brand']];
        }
        if ($param['category']) {
            $where[] = ['p.category', '=', $param['category']];
        }

        if ($param['user_id']) {
            $where[] = ['i.user_id', 'in', $param['user_id']];
        }
        if ($param['wid']) {
            $where[] = ['warehouse_id', '=', $param['wid']];
        }
        if ($param['is_futures'] != null) {
            $where[] = ['is_futures', '=', $param['is_futures']];
        }

        if ($param['start_time']) {
            $where[] = ['i.arrival_date', '>=', $param['start_time']];
        }
        if ($param['end_time']) {
            $where[] = ['i.arrival_date', '<=', $param['end_time']];
        }



        $warehouse = ModelWarehouse::where(['is_del' => 0, 'status' => '1'])->field('id,name,fl_warehouse_id')->select();
        $w = [];
        foreach ($warehouse as $value) {
            $w[$value['id']] = $value['fl_warehouse_id'];
        }

        $oWholesalOrderItemModel = Db::table('db_order_item')->alias('i')->field([
            'i.product_id',
            "GROUP_CONCAT( DISTINCT c.id) as user_id",
            "GROUP_CONCAT( c.cusname,' (',c.email,') ') as user",
            "GROUP_CONCAT( DISTINCT c.cusname) as user_name",
            'p.cname as product_name',
            'p.code',
            'p.brand',
            'p.hashrate as p_hashrate',
            'p.expiration_date',
            '(sum(i.pending_quantity) - sum(i.lock_qty))  as quantity',
            'i.warehouse_id as wid',
            'i.is_futures',
            'i.arrival_date',
            "GROUP_CONCAT( DISTINCT i.real_arrival_date ) as real_arrival_date",
            'p.billing_weight',
            'p.free_shipping',
            'p.apply_rules'

        ])

            ->leftJoin('db_product p', 'i.product_id = p.id')
            ->leftJoin('db_customer c', 'i.user_id = c.id')
            ->join('db_order w', 'i.order_id = w.id')
            ->where($where)
            ->where(function ($query) {
                $query->whereRaw('i.pending_quantity > i.lock_qty');
            })
            ->group('i.product_id, i.arrival_date, i.is_futures, i.warehouse_id, i.user_id');

        $oProductModel = new ProductModel();
        $enum = $oProductModel->getFieldEnum('comput_unit');
        $enumArr = $enum['comput_unit'];
        $total = $oWholesalOrderItemModel->count();
        $result = $oWholesalOrderItemModel->page($page, $limit)->select();

        $result = $result->toArray();
        $data = [];
        foreach ($result as $key => &$value) {
            $userArr = $value['user'] ? explode(',', $value['user']) : [];
            $value['user'] = reset($userArr);
            $value['brand'] = (int)$value['brand'];
           // $value['hashrate'] = $value['p_hashrate'] . (isset($enumArr[$value['computing_unit']]) ? $enumArr[$value['computing_unit']] : '');
            $value['fl_warehouse_id'] = $value['wid'];
            $value['is_fl_warehouse'] = 1;
            if (isset($w[$value['wid']])) {
                if ($w[$value['wid']]) {
                    $value['fl_warehouse_id'] = (int) $w[$value['wid']];
                    $value['is_fl_warehouse'] = 0;
                }
            }
        }

        $arrData['data'] = ['list' => $result, 'total' => $total];
        return $arrData;
    }

    public function resource($field)
    {
        $model = new WholesalOrderItemModel();
        $res = $model->getFieldEnum($field);
        return [
            'code' => 0,
            'data' => $res,
            'message' => '成功'
        ];
    }
}
